package com.sumer.psychology.sharing.infrastructure.persistence.hibernate;

import com.sumer.psychology.common.domain.model.Availability;
import com.sumer.psychology.common.persistence.hibernate.AbstractHibernateRepository;
import com.sumer.psychology.sharing.domain.model.SharedResource;
import com.sumer.psychology.sharing.domain.model.SharedResourceId;
import com.sumer.psychology.sharing.domain.model.SharedResourceRepository;
import org.hibernate.Query;

import java.util.UUID;

/**
 * 分享资源库
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/9/10
 * Time: 15:26
 */
public class HibernateSharedResourceRepository extends AbstractHibernateRepository implements SharedResourceRepository {
    @Override
    public SharedResourceId nextIdentity() {
        return new SharedResourceId(UUID.randomUUID().toString());
    }

    @Override
    public void add(SharedResource sharedResource) {
        session().saveOrUpdate(sharedResource);
    }

    @Override
    public SharedResource shareResourceOfId(SharedResourceId sharedResourceId) {
        Query query = session()
                .createQuery("from SharedResource where sharedResourceId=:sharedResourceId and availability=:availability")
                .setParameter("sharedResourceId", sharedResourceId)
                .setParameter("availability", Availability.ACTIVE);

        return (SharedResource) query.uniqueResult();
    }
}
